
package net.atremmedia.gwt.actionjava.examples.frame;

import actionjava.display.Bitmap;
import actionjava.display.BitmapData;
import actionjava.display.Graphics;
import actionjava.display.Shape;
import actionjava.events.mouse.MouseEvent;
import actionjava.events.mouse.MouseEvent.MouseEventType;
import actionjava.events.mouse.MouseOutHandler;
import actionjava.events.mouse.MouseOverHandler;
import actionjava.events.mouse.StageDownHandler;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;

public class AJExampleSourceButton
{
	private double x;
	private double y;
	private Shape buttonBG;
	private Bitmap buttonBitmap;
	private AJExampleOverview overview;
	private StageDownHandler downHandler = new StageDownHandler()
	{
		@Override
		protected void stageDownHandler(MouseEvent event)
		{
			Window.open(overview.getCurExample().getSrc(), "_blank", "");
		}
	};

	public AJExampleSourceButton(double x, double y, AJExampleOverview overview)
	{
		this.x = x;
		this.y = y;
		this.overview = overview;
		this.initialize();
	}

	private void initialize()
	{
		createBG();
		overview.addChild(buttonBG);

		createBackImg();
		overview.addChild(buttonBitmap);

		setEvents();
	}

	private void setEvents()
	{
		buttonBG.addEventListener(MouseEventType.MOUSE_OVER, new MouseOverHandler()
		{
			@Override
			protected void mouseOverHandler(MouseEvent event)
			{
				RootPanel.get().getElement().getStyle().setCursor(Cursor.POINTER);
				registerClickListener(true);
			}
		});

		buttonBG.addEventListener(MouseEventType.MOUSE_OUT, new MouseOutHandler()
		{
			@Override
			protected void mouseOutHandler(MouseEvent event)
			{
				RootPanel.get().getElement().getStyle().setCursor(Cursor.DEFAULT);
				registerClickListener(false);
			}
		});
	}

	private void registerClickListener(boolean register)
	{
		if(register) {
			overview.addEventListener(MouseEventType.STAGE_MOUSE_DOWN, downHandler);
		} else {
			RootPanel.get().getElement().getStyle().setCursor(Cursor.DEFAULT);
			overview.removeEventListener(MouseEventType.STAGE_MOUSE_DOWN, downHandler);
		}
	}

	private void createBG()
	{
		buttonBG = new Shape();
		buttonBG.setX(x);
		buttonBG.setY(y);
		buttonBG.setAlpha(.5);

		Graphics graphs = buttonBG.getGraphics();
		graphs.beginFill("#FFFFFF");
		graphs.drawRect(0, 0, 25, 25);
		graphs.endFill();
	}

	private void createBackImg()
	{
		buttonBitmap = new Bitmap(new BitmapData("img/srcButton.png"));
		buttonBitmap.setX(x);
		buttonBitmap.setY(y);
	}

	public void destroy()
	{
		registerClickListener(false);
		overview.removeChild(buttonBitmap);
		overview.removeChild(buttonBG);
	}
}
